package cn.itcast.handler;

import cn.itcast.message.LoginRequestMessage;
import cn.itcast.message.LoginResponseMessage;
import cn.itcast.server.service.UserService;
import cn.itcast.server.service.UserServiceFactory;
import cn.itcast.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Name: LoginRequestMessageHandler
 * @Description: 处理登陆请求的handler
 * @Author: Mr.Tong
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        //验证登陆请求
        String username = msg.getUsername();
        String password = msg.getPassword();
        UserService userService = UserServiceFactory.getUserService();
        boolean login = userService.login(username, password);

        LoginResponseMessage loginResponse;
        //判断登陆状态
        if (login) {
            loginResponse = new LoginResponseMessage(true, "登陆成功");
            //记录channel和username的映射关系-通过会话管理器
            SessionFactory.getSession().bind(ctx.channel(),username);
        } else {
            loginResponse = new LoginResponseMessage(false, "登陆失败");
        }

        //将服务器的用户名密码验证响应写入channel中
        ctx.writeAndFlush(loginResponse);

    }
}
